package com.itany.mall.service.proxy;

import java.util.Map;

import com.itany.mall.entity.OrderDetail;
import com.itany.mall.entity.User;
import com.itany.mall.exception.ServiceException;
import com.itany.mall.exception.UserNotFoundException;
import com.itany.mall.factory.Autowired;
import com.itany.mall.factory.Component;
import com.itany.mall.jdbc.transaction.TransactionManager;
import com.itany.mall.service.UserService;

@Component("userServiceProxy")
public class UserServiceProxy implements UserService {

	@Autowired
	private TransactionManager tm;

	@Autowired("userServiceImpl")
	private UserService impl;

	@Override
	public User login(String name, String password) throws UserNotFoundException, ServiceException {

		try {
			tm.beginTransaction();
			User u = impl.login(name, password);
			tm.commit();
			return u;
		} catch (UserNotFoundException e) {
			// 代理类没有权力处理实现类抛出的业务逻辑异常, 应该继续抛出
			// catch业务逻辑异常是为了按理事务, 而不是为了处理这个异常
			tm.rollback();
			throw e;
		} catch (Exception e) {
			// service层如果发生业务逻辑异常之外的其它异常
			// 统一转换为service异常抛出
			e.printStackTrace();
			tm.rollback();
			throw new ServiceException();
		}
	}

	@Override
	public void saveCart(Map<Long, OrderDetail> cart) throws ServiceException {
		try {
			tm.beginTransaction();
			impl.saveCart(cart);
			tm.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tm.rollback();
			throw new ServiceException();
		}
	}

	@Override
	public Map<Long, OrderDetail> loadCart(long userId) throws ServiceException {
		try {
			tm.beginTransaction();
			Map<Long, OrderDetail> map = impl.loadCart(userId);
			tm.commit();
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			tm.rollback();
			throw new ServiceException();
		}
	}

}
